// regex：使用mingw <regex.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

#define HOSTSDIR L"C:\\Windows\\System32\\drivers\\etc\\hosts"

char* ReadFileAll(wchar_t* fname) {
  HANDLE hFile = CreateFileW(fname, GENERIC_READ, FILE_SHARE_READ, NULL,
                             OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  LARGE_INTEGER fileSize;
  GetFileSizeEx(hFile, &fileSize);
  DWORD len = fileSize.QuadPart;
  char* str = malloc(len + 1);
  DWORD dwRead;
  ReadFile(hFile, str, len, &dwRead, NULL);
  CloseHandle(hFile);
  str[len] = '\0';
  return str;
}

char* getDate(char* str) {
  regex_t regex;
  regcomp(&regex, "Last updated: ([0-9\\-]+)", REG_EXTENDED);
  regmatch_t match[2] = {0};
  int res = regexec(&regex, str, 2, match, 0);
  if (res) return NULL;
  char* out = malloc(11);
  strncpy(out, str + match[1].rm_so, 10);
  out[10] = '\0';
  regfree(&regex);
  return out;
}

int wmain(int argc, wchar_t** argv) {
  char* str = ReadFileAll(HOSTSDIR);
  char* date = getDate(str);
  if (date) {
    printf("%s", date);
    free(date);
  } else {
    printf("No Match");
  }
  free(str);
  return 0;
}